﻿
using System;
using System.ServiceProcess;
using System.Management;

namespace WindowServices.Config
{
	/// <summary>
	/// ServiceControllerEx 的摘要说明。
	/// 这个类是用于扩展服务控制器的
	/// 可以控制服务的启动和停止
	/// 也可以改变服务的启动状态：手动、自动
	/// </summary>
	public class ServiceControllerEx:ServiceController
	{
		public ServiceControllerEx()
		{ }
		public ServiceControllerEx(string name):base(name)
		{ }
		public ServiceControllerEx(string name,string machineName):base(name,machineName)
		{ }
		public string Description
		{
			get
			{
				//construct the management path
				var path="Win32_Service.Name='"+ServiceName+"'";
				var p=new ManagementPath(path);
				//construct the management object
				var managementObj=new ManagementObject(p);
				return managementObj["Description"]!=null ? managementObj["Description"].ToString() : null;
			}
		}
		public string StartupType
		{
			get
			{
			    if (ServiceName == null)
			    {
			        return null;
			    }
			    //construct the management path
			    var path = "Win32_Service.Name='" + ServiceName + "'";
			    var p = new ManagementPath(path);
			    //construct the management object
			    var managementObj = new ManagementObject(p);
			    return managementObj["StartMode"].ToString();
			}
		    set
			{
				if(value!="Automatic" && value!="Manual" && value!="Disabled" && value != "Auto")
					throw new Exception("The valid values are Automatic, Manual or Disabled");

			    if (ServiceName == null) return;
			    //construct the management path
			    var path="Win32_Service.Name='"+ServiceName+"'";
			    var p=new ManagementPath(path);
			    //construct the management object
			    var managementObj=new ManagementObject(p);
			    //we will use the invokeMethod method of the ManagementObject class
			    var parameters=new object[1];
			    parameters[0]=value;
			    managementObj.InvokeMethod("ChangeStartMode",parameters);
			}
		}		
	}
}


